<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="渠道名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入渠道名称" />
      </el-form-item>
      <el-form-item label="渠道类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择渠道类型" style="width: 100%">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MEIJIA_CHANNEL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择员工" prop="systemUserCode">
        <el-select
          v-model="formData.systemUserCode"
          placeholder="请选择员工"
          filterable
          remote
          :remote-method="showEmployeeList"
        >
          <el-option
            v-for="employee in employeeList"
            :key="employee.systemUserCode"
            :label="employee.systemUserName + '-' + employee.phone"
            :value="employee.systemUserCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有推荐人" prop="hasReference">
        <el-radio-group v-model="formData.hasReference" class="ml-4">
          <el-radio :label="true" size="large">是</el-radio>
          <el-radio :label="false" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="推荐人员工"
        prop="referenceSystemUserCode"
        v-if="showReferenceSystemUserCode"
      >
        <el-select
          v-model="formData.referenceSystemUserCode"
          placeholder="请选择推荐人员工"
          remote
          :remote-method="showEmployeeReferenceList"
          reserve-keyword
          filterable
        >
          <el-option
            v-for="employeeReference in employeeReferenceList"
            :key="employeeReference.systemUserCode"
            :label="employeeReference.systemUserName + '-' + employeeReference.phone"
            :value="employeeReference.systemUserCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址搜索" v-show="formData.type == 'site'">
        <el-select
          v-model="keyword"
          placeholder=""
          filterable
          remote
          reserve-keyword
          :remote-method="handleSearch"
        >
          <el-option
            v-for="item in data1"
            :key="item.id"
            :value="item.id"
            :label="item.name"
            @click="handleSelect(item)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="address" v-show="formData.type == 'site'">
        <div id="map-box"></div>
        <div class="info-box">
          <a-tooltip>
            <template #title v-if="coord">点击复制</template>
            <span style="margin: 5px 8px">
              经纬度：<span class="copy" style="cursor: pointer" :data-clipboard-text="coord">{{
                coord
              }}</span>
            </span>
          </a-tooltip>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as HomeChannelApi from '@/api/meijia/home/channel'
import * as UserDetailApi from '@/api/system/user'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import AMapLoader from '@amap/amap-jsapi-loader'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  type: undefined,
  systemUserCode: undefined,
  hasReference: true,
  referenceSystemUserCode: undefined,
  longitude: undefined,
  latitude: undefined,
  address: undefined
})
const formRules = reactive({
  code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '渠道名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '渠道类型不能为空', trigger: 'change' }],
  systemUserCode: [{ required: true, message: '人员编号不能为空', trigger: 'blur' }],
  hasReference: [{ required: true, message: '是否有推荐人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const employeeList = ref()
const showEmployeeList = async (systemUserName: String) => {
  if (systemUserName) {
    employeeList.value = await UserDetailApi.getReferenceUserDetailByUserName(systemUserName)
  }
}
const showReferenceSystemUserCode = ref(true)
const employeeReferenceList = ref()
const showEmployeeReferenceList = async (systemUserName: String) => {
  if (systemUserName) {
    employeeReferenceList.value =
      await UserDetailApi.getReferenceUserDetailByUserName(systemUserName)
  }
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await HomeChannelApi.getHomeChannel(id)
      showEmployeeList(formData.value.systemUserName)
      if (formData.value.referenceSystemUserName) {
        showEmployeeReferenceList(formData.value.referenceSystemUserName)
      }
    } finally {
      formLoading.value = false
    }
  }
  initMap()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as HomeChannelApi.HomeChannelVO
    if (formType.value === 'create') {
      await HomeChannelApi.createHomeChannel(data)
      message.success(t('common.createSuccess'))
    } else {
      await HomeChannelApi.updateHomeChannel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    type: undefined,
    systemUserCode: undefined,
    hasReference: true,
    referenceSystemUserCode: undefined,
    longitude: undefined,
    latitude: undefined,
    address: undefined
  }
  formRef.value?.resetFields()
}

import { shallowRef, defineEmits, ref, onBeforeUnmount } from 'vue'
const map = shallowRef(null)
let AMapObj, placeSearch, marker, geocoder
const keyword = ref(null)
const data1 = ref([])
const coord = ref('')
function initMap() {
  AMapLoader.load({
    key: '219274a8a7fdbfbbf173473927a9e229', //设置您的key
    version: '2.0',
    plugins: ['AMap.ToolBar', 'AMap.Driving'],
    AMapUI: {
      version: '1.1',
      plugins: []
    },
    Loca: {
      version: '2.0.0'
    }
  })
    .then((AMap) => {
      console.log(AMap)
      AMapObj = AMap
      map.value = new AMap.Map('map-box', {
        viewMode: '3D',
        zoom: 10,
        zooms: [2, 22],
        center: [105.602725, 37.076636]
      })
      map.value.on('click', onMapClick)
      AMap.plugin(
        [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.Geolocation',
          'AMap.PlaceSearch',
          'AMap.Geocoder',
          'AMap.AutoComplete'
        ],
        () => {
          // 缩放条
          const toolbar = new AMap.ToolBar()
          // 比例尺
          const scale = new AMap.Scale()
          // 定位
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000, //超过10秒后停止定位，默认：5s
            position: 'RT', //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
          })
          geocoder = new AMap.Geocoder({
            city: '长沙'
          })
          map.value.addControl(geolocation)
          map.value.addControl(toolbar)
          map.value.addControl(scale)
          placeSearch = new AMap.PlaceSearch({
            // map: map.value,
            city: '长沙',
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            citylimit: false, // 是否强制限制在设置的城市内搜索
            autoFitView: true
          })
        }
      )
    })
    .catch((e) => {
      console.log(e)
    })
}
// 点击地图
function onMapClick(e) {
  coord.value = e.lnglat.lng + ',' + e.lnglat.lat
  geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress
    }
  })
  drawMarker(e.lnglat)
}

// 搜索地图
function handleSearch(str) {
  placeSearch.search(str, (status, result) => {
    console.log(result)
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois
      console.log(list)
      list.forEach((item) => {
        item.value = item.name
        item.label = item.name
      })
      data1.value = list
    }
  })
}
// 点击搜索项
function handleSelect(item) {
  drawMarker(item.location)
  if (item.location != null) {
    coord.value = item.location.lng + ',' + item.location.lat
  }
  formData.value.longitude = item.location.lng

  formData.value.address = item.name
  formData.value.latitude = item.location.lat
}
// 绘制地点marker
function drawMarker(location) {
  if (location == null) return
  let longitude = location.lng,
    latitude = location.lat
  if (marker) {
    marker.setMap(null)
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center'
  })
  marker.on('click', () => {
    coord.value = location
  })
  map.value.add(marker)
  map.value.setZoomAndCenter(16, [longitude, latitude])
  formData.value.longitude = location.lng
  formData.value.address = keyword
  formData.value.latitude = location.lat
}
watch(
  () => formData.value.hasReference,
  (New, Old) => {
    if (New == false) {
      formData.value.referenceSystemUserCode = undefined
      showReferenceSystemUserCode.value = false
    } else {
      showReferenceSystemUserCode.value = true
    }
  }
)
</script>
<style scoped>
.el-select {
  width: 100%;
}
#map-box {
  height: 300px;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
.info-box {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 300px;
  background-color: #1f1f1f;
  display: flex;
  flex-direction: column;
}
</style>
